package com.changgou.backend.utils;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class POIUtils {

    public static void writeExcel(String filepath, List<Map> list,List<String> columes,List<String> item){
        //在内存中创建一个Excel文件
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建工作表，指定工作表名称
        XSSFSheet sheet = workbook.createSheet("畅购订单列表");
        //创建行，0表示第一行
        XSSFRow row0 = sheet.createRow(0);
        for (int i = 0; i < columes.size(); i++) {
            row0.createCell(i).setCellValue(columes.get(i));
        }
        //数据从第二行还是写入
        for (int i = 1; i < list.size(); i++) {
            //获取每行
            XSSFRow row = sheet.createRow(i);
            //获取每个map
            Map map = list.get(i);
            Set set = map.entrySet();
            //获取每列数据并写入
            for (int j = 0; j < set.size(); j++) {
                try {
                    row.createCell(j).setCellValue((String) map.get(item.get(j)));
                } catch (Exception e) {
                    try {
                        row.createCell(j).setCellValue((Integer) map.get(item.get(j)));
                    } catch (Exception e1) {
                        Date date = (Date) map.get(item.get(j));
                        SimpleDateFormat sdp = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                        row.createCell(j).setCellValue(sdp.format(date));
                    }
                }
            }
        }
        //通过输出流将workbook对象下载到磁盘
        try {
            FileOutputStream out = new FileOutputStream(filepath);
            System.out.println();
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
